package com.qf.main.login.service.impl;

import com.alibaba.druid.util.StringUtils;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.qf.common.base.ex.ControllerException;
import com.qf.common.base.ex.PhoneCodeException;
import com.qf.common.base.ex.ServiceException;
import com.qf.common.base.result.ResultStatus;
import com.qf.common.base.snowflakeGenerator.SnowflakeGenerator;
import com.qf.common.oss.utils.FileUtils;
import com.qf.main.login.common.qo.SysRoleQo;
import com.qf.main.login.common.qo.SysUserQo;
import com.qf.main.login.common.vo.SysUserVo;
import com.qf.main.login.entity.RoleOperationPermission;
import com.qf.main.login.entity.SysRole;
import com.qf.main.login.entity.SysUser;
import com.qf.main.login.entity.UserRoleOperation;
import com.qf.main.login.mapper.RoleOperationPermissionMapper;
import com.qf.main.login.mapper.SysUserMapper;
import com.qf.main.login.mapper.UserRoleOperationMapper;
import com.qf.main.login.realm.UserToken;
import com.qf.main.login.service.SmsService;
import com.qf.main.login.service.SysUserService;
import com.qf.main.login.utils.CommonBeanutils;
import com.qf.main.login.utils.ShiroUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.ObjectUtils;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.IOException;
import java.io.Serializable;
import java.util.List;

/**
 * @author chengqiang
 * @Create 2024-01-18-21:19
 * @Description:
 */
@Service("SysUserService")
public class SysUserServiceImpl implements SysUserService {

    @Resource
    private SysUserMapper sysUserMapper;
    @Resource
    private UserRoleOperationMapper userRoleOperationMapper;

    @Resource
    private FileUtils fileUtils;



    public SysUser getSysUserInfo(String username) {
        return sysUserMapper.selectUserByName(username);
    }

    public SysUser getSysUserInfoByPhone(String phone){
        return sysUserMapper.selectUserByPhone(phone);
    }

    public SysUserVo login(UserToken userToken){
        Subject subject = SecurityUtils.getSubject();
        SysUser user = (SysUser) SecurityUtils.getSubject().getPrincipal();

        SysUser userInfo = sysUserMapper.selectUserByName(userToken.getUsername());
        if(ObjectUtils.isEmpty(userInfo)) {
            throw new ServiceException(ResultStatus.USER_DOES_NOT_EXIST);

        }
        if (userInfo.getDelStatus() != 0) {
            throw new ServiceException(ResultStatus.BANNED_USER);
        }
        try {
            // subject.login(new UserToken(username, password));
            subject.login(userToken);
        }
         catch (IncorrectCredentialsException ice) {
            // 转化成自定义异常
            throw new ServiceException(ResultStatus.USER_USERNAME_PASSWORD);
        }
        catch (AuthenticationException ae) {
            throw new ServiceException(ResultStatus.USER_LOGIN_ERROR);
        }
        SysUser principal = (SysUser) SecurityUtils.getSubject().getPrincipal();
        SysUserVo sysUserVo = CommonBeanutils.convertTo(principal, SysUserVo::new);
        sysUserVo.setToken(subject.getSession().getId().toString());
        return sysUserVo;
    }

    @Override
    public PageInfo<SysUserVo> getSysUserList(String username, String phone, Integer pageNum, Integer pageSize) {


        return null;
    }

    @Override
    public PageInfo<SysUserVo> listUser(String username,String phone, Integer pageNum, Integer pageSize) {
        PageInfo<SysUserVo> PageInfo = PageHelper.startPage(pageNum, pageSize).doSelectPageInfo(
                () -> sysUserMapper.selectUserList(username,phone));
        return PageInfo;
    }
    // @Override
    // public PageInfo<SysUserVo> listUser(String username,String phone, Integer pageNum, Integer pageSize) {
    //     QueryWrapper<SysUser> qw = new QueryWrapper<SysUser>();
    //     qw.like(!StringUtils.isEmpty(username),SysUser.COL_USERNAME,username);
    //     qw.like(!StringUtils.isEmpty(phone),SysUser.COL_PHONE,phone);
    //
    //     PageInfo<SysUserVo> PageInfo = PageHelper.startPage(pageNum, pageSize).doSelectPageInfo(
    //             () -> sysUserMapper.selectList(qw));
    //     return PageInfo;
    // }

    @Override
    public Integer removeUser(Integer id) {

        return sysUserMapper.deleteById(id);
    }

    @Override
    public Integer recoverUser(Integer id) {
        return sysUserMapper.recoverUser(id);
    }

    @Override
    public String uploadImage(MultipartFile multipartFile, String path) {
        String fileName;
        try {
            fileName= fileUtils.uploadImage(multipartFile, path);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        return fileName;
    }

    @Override
    @Transactional
    public Integer saveSysUser(SysUserQo sysUserQo) {
        if(!ObjectUtils.isEmpty(sysUserMapper.selectUserByName(sysUserQo.getUsername()))){
            throw new ServiceException(ResultStatus.USER_DOES__EXIST);
        }
        if(!ObjectUtils.isEmpty(sysUserMapper.selectUserByPhone(sysUserQo.getPhone()))){
            throw new ServiceException(ResultStatus.PHONE_DOES__EXIST);
        }
        SysUser sysUser = CommonBeanutils.convertTo(sysUserQo, SysUser::new);
        if(!StringUtils.isEmpty(sysUser.getPassword())){
            sysUser.setPassword(ShiroUtils.encryption(sysUser.getPassword()));
        }
        long l = SnowflakeGenerator.generateId();
        int l1 = (int) l;
        sysUser.setId(l1);
        int insert = sysUserMapper.insert(sysUser);
        Integer roleId = sysUserQo.getRoleId();
        UserRoleOperation userRoleOperation = new UserRoleOperation();
        userRoleOperation.setRoleId(roleId);
        userRoleOperation.setUserId(l1);
        userRoleOperationMapper.insert(userRoleOperation);
        return insert;
    }

    @Override
    @Transactional
    public Integer modifySysUserPassword(SysUserQo sysUserQo, String oldPassword, String ConfirmPassword) {
        // qo转po
        SysUser sysUser = CommonBeanutils.convertTo(sysUserQo, SysUser::new);
        // 条件构造器
        QueryWrapper<SysUser> qw = new QueryWrapper();
        qw.eq(SysUser.COL_USERNAME,sysUser.getUsername()).eq(SysUser.COL_PASSWORD, ShiroUtils.encryption(oldPassword));
        // 通过账号密码获取寻找
        SysUser sysUser1 = sysUserMapper.selectOne(qw);

        // 修改密码

        if(!StringUtils.isEmpty(sysUser.getPassword())){
            if (!sysUser.getPassword().equals(ConfirmPassword)) {
                // 确认密码不一致
                throw new ControllerException(ResultStatus.PASSWORD_CONFIRM_NOT);
            }
            if(ObjectUtils.isEmpty(sysUser1)){
                // 用户名或密码错误
                throw new ControllerException(ResultStatus.USER_NO_EXIST);
            }

            sysUser.setPassword(ShiroUtils.encryption(sysUser.getPassword()));

        }

        // 修改角色类型
        if(sysUserQo.getRoleId()!=null&&sysUserQo.getRoleId() != 0){
            // 修改角色
            UserRoleOperation userRoleOperation = new UserRoleOperation();
            userRoleOperation.setRoleId(sysUserQo.getRoleId());
            userRoleOperationMapper.update(userRoleOperation,new QueryWrapper<UserRoleOperation>().eq(UserRoleOperation.COL_USER_ID,sysUser1.getId()));
        }

        // 修改其他
        return sysUserMapper.update(sysUser, qw);
    }

    @Override
    public Integer modifySysUser(SysUserQo sysUserQo) {
        SysUser sysUser = CommonBeanutils.convertTo(sysUserQo, SysUser::new);
        sysUserMapper.updateById(sysUser);

        UserRoleOperation userRoleOperation = new UserRoleOperation();
        userRoleOperation.setRoleId(sysUserQo.getRoleId());
        userRoleOperation.setUserId(sysUserQo.getId());
        QueryWrapper<UserRoleOperation> qroQw = new QueryWrapper<>();
        qroQw.eq(UserRoleOperation.COL_USER_ID,sysUserQo.getId());
        userRoleOperationMapper.update(userRoleOperation ,qroQw);
        return 1;
    }










}
